package cn.com.easy.permission.job;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.com.easy.permission.dao.OptionLogDao;
import cn.com.easy.permission.model.OptionLogModel;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 操作日志定时提交到后台
 * 
 * @author nibili 2018年7月11日
 * 
 */
@Component
public class SaveOptionLogModelJob {

	/** 操作日志dao */
	@Autowired
	private OptionLogDao optionLogDao;
	/** 线程 id 和 操作日志集合 map */
	private Map<Long, List<OptionLogModel>> map = Maps.newConcurrentMap();

	@Scheduled(cron = "0/5 * * * * ? ")
	public void start() {
		synchronized (this) {
			OptionLogModel optionLogModel;
			for (Long threadId : map.keySet()) {
				//
				List<OptionLogModel> list = map.get(threadId);
				//
				if (CollectionUtils.isNotEmpty(list) == true) {
					//
					Iterator<OptionLogModel> iterator = list.iterator();
					while (iterator.hasNext() == true) {
						optionLogModel = iterator.next();
						optionLogDao.save(optionLogModel);
						iterator.remove();
					}
				}
			}
		}
	}

	/**
	 * 添加 操作日志
	 * 
	 * @param threadId
	 * @param model
	 * @auth nibili 2018年7月11日
	 */
	public void addModel(Long threadId, OptionLogModel optionLogModel) {
		synchronized (this) {
			List<OptionLogModel> list = map.get(threadId);
			if (list == null) {
				list = Lists.newArrayList();
				map.put(threadId, list);
			}
			list.add(optionLogModel);
		}
	}
}
